using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.XPath;
using Fuzzware.Common.Encoding;
using Fuzzware.Common.DataSchema;

namespace Fuzzware.ConvertFromXML.Processors
{
    class CountFn
    {
        /// <summary>
        /// Use XPathNav to count the number of occurrences of the SourceNode
        /// </summary>
        public void Count(ref byte[] operand, IOutputNode SourceNode, IOutputNode TargetNode)
        {
            int Count = 0;

            if (null != SourceNode.XPathNav)
            {
                XPathNavigator XPathNav = SourceNode.XPathNav.Clone();
                
                // Make sure our source node XPathNav points to the first instance of this node type
                // while (XPathNav.MoveToPrevious()) ;

                // Move forward through the siblings until there are no more siblings
                Count = 0;
                do
                {
                    // Only count node that are elements
                    if (XPathNav.NodeType == XPathNodeType.Element)
                        Count++;
                }
                while (XPathNav.MoveToNext());
            }

            String EncValue = Count.ToString();
            if (Coder.NeedsEncoding(TargetNode.TypeCode))
                EncValue = Coder.MakeEncoded(BitConverter.GetBytes(Count), TargetNode.TypeCode);

            operand = TargetNode.OutputEncoding.GetBytes(EncValue);
        }
    }
}
